package cn.merlulin.monitor.sdk.appender;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import ch.qos.logback.core.UnsynchronizedAppenderBase;
import cn.merlulin.monitor.sdk.model.LogMessage;
import cn.merlulin.monitor.sdk.push.IPush;
import cn.merlulin.monitor.sdk.push.impl.RedisPush;

import java.util.Arrays;

/**
 * @author Merlin
 * @version 1.0
 * @email 756151581@qq.com
 * @desc 自定义日志采集
 * @date 2025/1/15 15:11
 */
public class CustomerAppender<E> extends UnsynchronizedAppenderBase<E> {

    // 系统名称
    private String systemName;
    // 只采集指定范围的日志
    private String groupId;
    // redis 连接地址
    private String host;
    // redis 连接端口
    private int port;

    private final IPush push = new RedisPush();

    @Override
    public void start() {
        push.open(host, port);
        super.start();
    }

    @Override
    protected void append(E eventObject) {

        if (eventObject instanceof ILoggingEvent) {
            ILoggingEvent event = (ILoggingEvent) eventObject;

            String methodName = "unknown";
            String className = "unknown";

            StackTraceElement[] callerDataArray = event.getCallerData();
            if (null != callerDataArray && callerDataArray.length > 0) {
                StackTraceElement callerData = callerDataArray[0];
                className = callerData.getClassName();
                methodName = callerData.getMethodName();
            }

            // 只采集指定范围的日志
            if (!className.startsWith(groupId)) {
                return;
            }

            LogMessage logMessage = new LogMessage(systemName, className, methodName, Arrays.asList(event.getFormattedMessage().split(" ")));
            push.send(logMessage);
        }
    }

    public String getSystemName() {
        return systemName;
    }

    public void setSystemName(String systemName) {
        this.systemName = systemName;
    }

    public String getGroupId() {
        return groupId;
    }

    public void setGroupId(String groupId) {
        this.groupId = groupId;
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }
}
